package com.bestcem.xm.qdes.grpc.service;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bestcem.xm.messagecenter.grpc.v1.services.*;
import com.bestcem.xm.qdes.entity.MessageTemplate;
import com.bestcem.xm.qdes.service.MessageService;
import io.grpc.stub.StreamObserver;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;

import java.util.List;
import java.util.Objects;

import static com.bestcem.xm.qdes.grpc.service.GrpcConstant.FAIL_STATUS;
import static com.bestcem.xm.qdes.grpc.service.GrpcConstant.SUCCESS_STATUS;


/**
 * 消息模板相关gRpc接口
 *
 * @author xiaoshu.shao <xiaoshu.shao@idiaoyan.com>
 * @version V1.0
 * @date 2022/8/9
 */
@GrpcService
@Slf4j
@RequiredArgsConstructor
public class MessagecenterGrpcService extends MessagecenterServiceGrpc.MessagecenterServiceImplBase {

    private @NonNull MessageService messageService;

    private static final String DEFAULT_MESSAGE_TEMPLATE_FILE_PATH = "file/default_message_template.json";

    /**
     * 获取消息默认模板
     *
     * @param request          请求
     * @param responseObserver 返回
     */
    @Override
    public void getDefaultTemplate(GetDefaultTemplateRequest request, StreamObserver<GetDefaultTemplateResponse> responseObserver) {
        GetDefaultTemplateResponse.Builder builder = GetDefaultTemplateResponse.newBuilder();
        LambdaQueryWrapper<MessageTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MessageTemplate::getOrgId, request.getOrgId())
                .eq(MessageTemplate::getTtype, request.getType().getNumber())
                .eq(MessageTemplate::getScenario, request.getScenario().getNumber())
                .eq(MessageTemplate::getDefaultTemplate, "默认模板");
        List<MessageTemplate> templateData = messageService.list(queryWrapper);
        templateData.stream().findFirst()
                .ifPresent(template -> {
                    builder.setContent(template.getTemplate());
                    builder.setSubject(template.getEmailTitle());
                });
        /*if (!CollectionUtils.isEmpty(templateData)) {
            MessageTemplate template = templateData.get(0);
            builder.setContent(template.getTemplate());
            builder.setSubject(template.getEmailTitle());
        }*/
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void getMessageTemplateById(GetMessageTemplateByIdRequest request, StreamObserver<GetMessageTemplateByIdResponse> responseObserver) {
        GetMessageTemplateByIdResponse.Builder builder = GetMessageTemplateByIdResponse.newBuilder();
        MessageTemplate template = messageService.getById(request.getId());
        if (Objects.nonNull(template)) {
            MessageCenterTemplate.Builder messageTemplate = MessageCenterTemplate.newBuilder();
            messageTemplate.setTemplate(template.getTemplate());
            builder.setMessageCenterTemplate(messageTemplate);
            builder.setStatus(SUCCESS_STATUS);
        } else {
            builder.setStatus(FAIL_STATUS);
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void initDefaultTemplate(InitDefaultTemplateRequest request, StreamObserver<InitDefaultTemplateResponse> responseObserver) {
        InitDefaultTemplateResponse.Builder builder = InitDefaultTemplateResponse.newBuilder();
        String orgId = request.getOrgId();
        if (StrUtil.isBlankIfStr(orgId)) {
            log.error("initDefaultTemplate orgId 不能为空");
            builder.setStatus(FAIL_STATUS);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        long count = messageService.count(Wrappers.<MessageTemplate>lambdaQuery().eq(MessageTemplate::getOrgId, orgId).eq(MessageTemplate::getDefaultTemplate, "默认模板"));
        if (count > 0) {
            log.error("默认模板已存在！");
            builder.setStatus(FAIL_STATUS);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        String json = ResourceUtil.readUtf8Str(DEFAULT_MESSAGE_TEMPLATE_FILE_PATH);
        List<MessageTemplate> entityList = JSON.parseArray(json, MessageTemplate.class);
        entityList.forEach(it -> {
            it.setDeleted(Boolean.FALSE);
            it.setOrgId(orgId);
            it.setTitle("默认模板");
            it.setIsDefault(Boolean.FALSE);
            it.setUseStatus(0);
            it.setStatus(0);
            it.setDefaultTemplate("默认模板");
        });
        messageService.saveBatch(entityList, 20);
        builder.setStatus(SUCCESS_STATUS);
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}
